package com.boesch.electroOffice.dataaccess.daoImpl.messerli;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.boesch.electroOffice.dataaccess.common.IllegalDataAccessException;
import com.boesch.electroOffice.dataaccess.common.ReturnCodesDataaccess;
import com.boesch.electroOffice.dataaccess.dao.messerli.InvoiceDao;
import com.boesch.electroOffice.dataaccess.mapper.messerli.InvoiceMesserliMapper;
import com.boesch.electroOffice.model.messerli.Invoice;

/**
 * This class executes the sql statements on the messerli database for class invoice.
 * If a Exception is thrown, 
 * it will be unpacked to a illegalDataAccessException 
 * including a return code which can be shown to the user.
 * 
 * @author Ralph Koster
 * 
 */
@Repository
public class InvoiceDaoImpl implements InvoiceDao, Serializable {

	private static final long serialVersionUID = -4421771808104884279L;

	@Autowired
	private JdbcTemplate mfJdbcTemplate;

	@Value("${messerli.queryReadAllInvoices}")
	private String queryReadAllInvoices;
	@Value("${messerli.queryReadInvoiceByInvoiceNumber}")
	private String queryReadInvoiceByInvoiceNumber;

	/**
	 * {@inheritDoc}
	 */
	public List<Invoice> readAllInvoices() throws IllegalDataAccessException {
		List<Invoice> invoices = new ArrayList<Invoice>();
		try {
			invoices = mfJdbcTemplate.query(queryReadAllInvoices, new InvoiceMesserliMapper());
			return invoices;
		} catch (DataAccessException e) {
			throw new IllegalDataAccessException(ReturnCodesDataaccess.NO_OBJECTS_FOUND_ERROR.getValue(), e);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public Invoice readInvoiceByInvoiceNumber(String invoiceNumber) throws IllegalDataAccessException {
		Invoice invoice = null;
		List<Invoice> invoices = mfJdbcTemplate.query(queryReadInvoiceByInvoiceNumber, new Object[] { invoiceNumber }, new InvoiceMesserliMapper());
		if (null != invoices && invoices.size() == 1) {
			invoice = invoices.get(0);
			return invoice;
		} else {
			throw new IllegalDataAccessException(ReturnCodesDataaccess.OBJECT_NOT_FOUND_ERROR.getValue());
		}
	}
}
